package com.weitu.occupationalHealth.phyData.controller;

import com.alibaba.fastjson.JSONArray;
import com.weitu.accessory.bean.AccessoryPackageInfo;
import com.weitu.accessory.service.AccessoryUtilService;
import com.weitu.accessory.util.AccessoryUtil;
import com.weitu.base.annotaion.SystemLog;
import com.weitu.base.constant.DictionaryTypeDefConstants;
import com.weitu.base.controller.BaseController;
import com.weitu.occupationalHealth.phyData.entity.PhyData;
import com.weitu.occupationalHealth.phyData.service.OccDoubtService;
import com.weitu.occupationalHealth.phyData.service.OccForbidService;
import com.weitu.occupationalHealth.phyData.service.OccOtherService;
import com.weitu.occupationalHealth.phyData.service.PhyDataService;
import com.weitu.paging.DataGridPagination;
import com.weitu.permission.dictionary.service.DictionaryService;
import com.weitu.permission.user.entity.User;
import com.weitu.plugin.PageView;
import com.weitu.util.AjaxResult;
import com.weitu.util.DateTimeUtil;
import com.weitu.util.IDGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.weitu.util.AjaxResult.fail;
import static com.weitu.util.AjaxResult.success;
import com.weitu.util.TableTreeNodeUtil;
/**
 * Created by WT-SUN on 2017/4/15.
 */
@Controller
@RequestMapping(value = "occupationalHealth/phyData")
public class PyhDataController extends BaseController {

    private static final String MODULE_BATH_PATH = BASE_JSP_PATH + "occupationalHealth/phyData/";

    @Autowired
    private PhyDataService phyDataService;

    @Autowired
    private DictionaryService dictionaryService;

    @Autowired
    private OccDoubtService occDoubtService;

    @Autowired
    private OccForbidService occForbidService;

    @Autowired
    private OccOtherService occOtherService;

    @Autowired
    private AccessoryUtilService accessoryUtilService;
    /**
     * 跳转
     *
     * @return
     */
    @RequestMapping(value = "/list")
    public String list() {
        return MODULE_BATH_PATH + "list";
    }

    /**
     * 个人体检数据
     * @return
     */
    @RequestMapping(value = "/person/list")
    public String personList(){
        return MODULE_BATH_PATH + "personList";
    }

    @RequestMapping("add")
    public ModelAndView add() {
        ModelAndView modelAndView = new ModelAndView();
        List<Map<String,Object>> con =dictionaryService.queryDictionaryByDictionaryTypeCode(DictionaryTypeDefConstants.OHE_HEALTH_CONCLUSION);
        modelAndView.addObject("con", con);
        modelAndView.setViewName(MODULE_BATH_PATH + "add");
        return modelAndView;
    }
    /**
     * 跳转详情与编辑页面
     *
     * @param id
     * @return
     */
    @RequestMapping("info")
    public ModelAndView info(String id, String type) {
        ModelAndView modelAndView = new ModelAndView();
        PhyData phyData=phyDataService.selectById(id);
        List<AccessoryPackageInfo> accessoryList = accessoryUtilService.queryAccessoryByBusinessId(id);
        List<Map<String,Object>> con =dictionaryService.queryDictionaryByDictionaryTypeCode(DictionaryTypeDefConstants.OHE_HEALTH_CONCLUSION);
        modelAndView.addObject("con", con);
        modelAndView.addObject("phy", phyData);
        modelAndView.addObject("accessoryList",accessoryList);
        if (type.equals("info")) {
            modelAndView.setViewName(MODULE_BATH_PATH + "info");
        } else {
            modelAndView.setViewName(MODULE_BATH_PATH + "edit");
        }
        return modelAndView;
    }

    /**
     * 体检异常处置
     * @return
     */
    @RequestMapping(value = "abnormal/list")
    public String abnormalList() {
        return MODULE_BATH_PATH + "abnormalList";
    }

    @RequestMapping(value = "/a/list")
    public String alist() {
        return MODULE_BATH_PATH + "analysis";
    }
    /**
     * 个人体检异常处置
     * @return
     */
    @RequestMapping(value = "/pAb/list")
    public String pAbList() {
        return MODULE_BATH_PATH + "pAbList";
    }

    /**
     * 体检异常数据页面
     * @return
     */
    @RequestMapping("abnormal")
    public ModelAndView abnormal(String id,String type){
        ModelAndView modelAndView = new ModelAndView();
        PhyData phyData=phyDataService.selectById(id);
        List<AccessoryPackageInfo> accessoryList = accessoryUtilService.queryAccessoryByBusinessId(id);
        List<Map<String,Object>> con =dictionaryService.queryDictionaryByDictionaryTypeCode(DictionaryTypeDefConstants.OHE_HEALTH_CONCLUSION);
        List<Map<String,Object>> op =dictionaryService.queryDictionaryByDictionaryTypeCode(DictionaryTypeDefConstants.OHE_HEALTH_OPTIONS);//
        List<Map<String,Object>> re =dictionaryService.queryDictionaryByDictionaryTypeCode(DictionaryTypeDefConstants.OHE_HEALTH_REVIEWINFO);
        List<Map<String,Object>> zy =dictionaryService.queryDictionaryByDictionaryTypeCode(DictionaryTypeDefConstants.OHE_DIAGNOSIS_TYPE);
        modelAndView.addObject("zy", zy);
        modelAndView.addObject("re", re);
        modelAndView.addObject("op", op);
        modelAndView.addObject("con", con);
        modelAndView.addObject("phy", phyData);
        modelAndView.addObject("accessoryList",accessoryList);
        if ("edit".equals(type)){
            modelAndView.setViewName(MODULE_BATH_PATH + "abnormal");
        }
        else {
            modelAndView.setViewName(MODULE_BATH_PATH + "abnormalInfo");
        }
        return modelAndView;
    }
    /**
     * 添加
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("insertYcSelective")
    @SystemLog(module = "职业卫生——体检异常处置", methods = "体检异常处置")
    @Transactional
    public AjaxResult insertYcSelective(HttpServletRequest request, HttpServletResponse response){
        Map<String, Object> paramMap = new HashMap<String, Object>();
        getAddBasicFieldMap(paramMap);
        paramMap.put("delState",0);
        String phyId=paramMap.get("phyId").toString();
        boolean accFlag= AccessoryUtil.saveAccerssoryInfo(phyId);
        boolean boo=phyDataService.insertYcData(paramMap);
        if (boo) {
            return success("添加成功");
        }else {
            return fail("添加失败");
        }
    }

    /**
     * 编辑
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("updateSelective")
    @SystemLog(module = "职业卫生——体检数据", methods = "编辑体检数据")
    @Transactional
    public AjaxResult updateSelective(HttpServletRequest request, HttpServletResponse response){
        Map<String, Object> paramMap = new HashMap<String, Object>();
        getEditBasicFieldMap(paramMap);
        paramMap.put("delState",0);
        String phyId=paramMap.get("id").toString();
        int boo=0;
        boo=phyDataService.updateByIdSelective(paramMap);
        String oldOptions=paramMap.get("oldOptions").toString();
        String newOptions=paramMap.get("options").toString();
        if (!oldOptions.equals(newOptions)){
            phyDataService.deleteYcData(phyId);
        }
        if (boo > 0) {
            if (paramMap.get("conclusion")!=null){
                List<Map> list=new ArrayList<Map>();
                if (paramMap.get("conclusion")instanceof String){
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("phyId",phyId);
                    map.put("conclusionId",paramMap.get("conclusion").toString());
                    map.put("delState",0);
                    list.add(map);
                }else {
                    List<String> conIds=(List<String>)paramMap.get("conclusion");
                    if(conIds!=null&& !"".equals(conIds)){
                        if (conIds.size()>0){
                            for (String conid:conIds){
                                Map<String, Object> map = new HashMap<String, Object>();
                                map.put("phyId",phyId);
                                map.put("conclusionId",conid);
                                map.put("delState",0);
                                list.add(map);
                            }
                        }
                    }
                }
                int dboo=phyDataService.deleteConclusions(phyId);
                int cboo=phyDataService.insertConclusions(list);
            }
            boolean accFlag= AccessoryUtil.saveAccerssoryInfo(phyId);
            if (accFlag){
                boolean falg= addEditTable(paramMap);
                if (falg){
                    return success("添加成功");
                }else {
                    return fail("添加失败");
                }
            }else {
                return fail("添加失败");
            }
        } else {
            return fail("添加失败");
        }
    }

    /**
     * 添加
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("insertSelective")
    @SystemLog(module = "职业卫生——体检数据", methods = "添加体检数据")
    @Transactional
    public AjaxResult insertSelective(HttpServletRequest request, HttpServletResponse response){
        Map<String, Object> paramMap = new HashMap<String, Object>();
        getAddBasicFieldMap(paramMap);
        paramMap.put("delState",0);
        String phyId=paramMap.get("id").toString();
        int boo=0;
        boo=phyDataService.insertSelective(paramMap);
        if (boo > 0) {
            if (paramMap.get("conclusion")!=null){
                List<Map> list=new ArrayList<Map>();
                if (paramMap.get("conclusion")instanceof String){
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("phyId",phyId);
                    map.put("conclusionId",paramMap.get("conclusion").toString());
                    map.put("delState",0);
                    list.add(map);
                }else {
                    List<String> conIds=(List<String>)paramMap.get("conclusion");
                    if(conIds!=null&& !"".equals(conIds)){
                        if (conIds.size()>0){
                            for (String conid:conIds){
                                Map<String, Object> map = new HashMap<String, Object>();
                                map.put("phyId",phyId);
                                map.put("conclusionId",conid);
                                map.put("delState",0);
                                list.add(map);
                            }
                        }
                    }
                }
                int cboo=phyDataService.insertConclusions(list);
            }
            if (paramMap.get("zyweihai")!=null){
                List<Map> list=new ArrayList<Map>();
                String conIdsp= paramMap.get("zyweihai").toString();
                String[] conIds=null;
                conIds=conIdsp.split(",");
                for (String conid:conIds){
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("phyId",phyId);
                    map.put("harmId",conid);
                    map.put("delState",0);
                    list.add(map);
                }
                int cboo=phyDataService.insertHarmIds(list);
            }
            boolean accFlag= AccessoryUtil.saveAccerssoryInfo(phyId);
            if (accFlag){
                boolean falg= addEditTable(paramMap);
                if (falg){
                    return success("添加成功");
                }else {
                    return fail("添加失败");
                }
            }else {
                return fail("添加失败");
            }
        } else {
            return fail("添加失败");
        }
    }

    private Boolean addEditTable(Map<String,Object> map){
        Map<String, Object> paramMap = new HashMap<String, Object>();
        boolean flag=false;
        User loginUser= getSessionUser();
        String phyId=map.get("id").toString();
        String dateTime=DateTimeUtil.formatterDateTime();
        String loginUserId=loginUser.getId();
        String loginUserDeptId=loginUser.getDepartment().getId();
        boolean occforbidFalg=false;
        boolean occdoubtFalg=false;
        boolean occotherFalg=false;
        if (map.get("occforbidTb")!=null){
            String dataStr = map.get("occforbidTb").toString();
            List<Map> list=addEditTableList(dataStr,phyId,dateTime,loginUserId,loginUserDeptId);
            paramMap.put("occForbidList",list);
            int dboo=occForbidService.deleteById(phyId);
            int boo=occForbidService.insert(paramMap);
            if (boo>0){
                occforbidFalg=true;
            }
        }else {
            int dboo=occForbidService.deleteById(phyId);
            occforbidFalg=true;
        }
        if (map.get("occdoubtTb")!=null){
            String dataStr = map.get("occdoubtTb").toString();
            List<Map> list=addEditTableList(dataStr,phyId,dateTime,loginUserId,loginUserDeptId);
            paramMap.put("occDoubtList",list);
            int dboo=occDoubtService.deleteById(phyId);
            int boo=occDoubtService.insert(paramMap);
            if (boo>0){
                occdoubtFalg=true;
            }
        }else {
            int dboo=occForbidService.deleteById(phyId);
            occdoubtFalg=true;
        }
        if (map.get("occotherTb")!=null){
            String dataStr = map.get("occotherTb").toString();
            List<Map> list=addEditTableList(dataStr,phyId,dateTime,loginUserId,loginUserDeptId);
            paramMap.put("occOtherList",list);
            int dboo=occOtherService.deleteById(phyId);
            int boo=occOtherService.insert(paramMap);
            if (boo>0){
                occotherFalg=true;
            }
        }else {
            int dboo=occForbidService.deleteById(phyId);
            occotherFalg=true;
        }
        return  occforbidFalg&&occdoubtFalg&&occotherFalg;
    }

    private List<Map> addEditTableList(String dataStr,String phyId,String dateTime,String loginUserId,String loginUserDeptId){
        List<Map> list = JSONArray.parseArray(dataStr,Map.class);
        for(Map m:list){
            String uuid = IDGenerator.getId();
            m.put("id",uuid);
            m.put("delState",0);
            m.put("phyDataId",phyId);
            m.put("addTime", dateTime);
            m.put("addUserId", loginUserId);
            m.put("addDeptId", loginUserDeptId);
        }
        return list;
    }

    /**
     * 体检数据列表
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/phyTable", method = RequestMethod.POST)
    public Object phyTable(HttpServletRequest request) throws Exception {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        putParametersIntoMap(paramMap);
        if (paramMap.get("persion")!=null){
            User loginUser= getSessionUser();
            String loginUserId=loginUser.getId();
            paramMap.put("userId",loginUserId);
        }
        int totalNum=phyDataService.selectAllPhyCount(paramMap);
        DataGridPagination dataGridPagination= DataGridPagination.getInstance(request,totalNum);
        PageView pageView=dataGridPagination.getPageView();
        if (paramMap.get("sort") == null) {
            pageView.setSortColumn("addTime");
        }
        paramMap.put("pageView", pageView);
        List<PhyData> maps=phyDataService.selectAllPhy(paramMap);
        Object data=dataGridPagination.flushDataGridData(maps);
        return data;
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping("deleteById")
    @Transactional
    @SystemLog(module = "职业卫生——防护设施", methods = "删除防护设施")
    public AjaxResult deleteById(String id){
        int boo=phyDataService.deleteByIdAll(id);
        if (boo > 0) {
            return success("删除成功");
        } else {
            return fail("删除失败");
        }
    }

    @SystemLog(module = "职业卫生", methods = "职业病诊断附件")
    @ResponseBody
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public AjaxResult upload(String id) throws Exception {
        if (!AccessoryUtil.saveAccerssoryInfo(id)) {
            return fail("附件信息保存失败！");
        }
        return success("附件信息保存成功！");
    }

    /**
     * 统计分析
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/selectAnalysis", method = RequestMethod.POST)
    public List<Map<String,Object>> selectAnalysis(HttpServletRequest request) throws Exception{
        Map<String, Object> paramMap = new HashMap<String, Object>();
        putParametersIntoMap(paramMap);
        List<Map<String,Object>> maps=phyDataService.selectAnalysis(paramMap);
        List<Map<String,Object>> mapList=TableTreeNodeUtil.getFatherNode(maps);
        return mapList;
    }
}
